package com.zust513.controller;


import com.zust513.entity.Account;
import com.zust513.entity.Order;
import com.zust513.entity.Transaction;
import com.zust513.entity.User;
import com.zust513.service.ClientService;
import com.zust513.utils.ServletContextUtil;
import lombok.RequiredArgsConstructor;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import java.awt.print.Pageable;
import java.math.BigDecimal;
import java.util.List;

@Controller
@RequestMapping("clients")
@RequiredArgsConstructor
public class ClientController {
    final ClientService clientService;
    final PasswordEncoder passwordEncoder;


    @GetMapping("clientmain")
    public String clientMain(ModelMap modelMap,
                             @RequestParam(value = "page", defaultValue = "1") int page,
                             @RequestParam(value = "size", defaultValue = "8") int size) {
        User clientUser = ServletContextUtil.getCurUser();
        List<Order> orders=clientService.getOrdersByUserId(clientUser.getUserId());
        int totalpages = (int) Math.ceil((double) orders.size() / size);
        modelMap.addAttribute("orders", orders);
        modelMap.addAttribute("user", clientUser);
        modelMap.addAttribute("currentPage", page);
        modelMap.addAttribute("totalPages", totalpages);
        return "Clients/Main";
    }

    @GetMapping("clientorderdetail")
    public String clientOrderDetail(ModelMap modelMap,@RequestParam(value = "orderId") int orderId) {
        User clientUser=ServletContextUtil.getCurUser();
        Order order=clientService.selectOrderByOrderId(orderId);
        modelMap.addAttribute("order", order);
        modelMap.addAttribute("user",clientUser);
        return "Clients/Orderdetail";
    }

    //修改订单状态
    @PostMapping("clientorderdetail")
    public String clientPostOrderDetail(ModelMap modelMap,@RequestParam("orderId") int orderId) {
        User clientUser=ServletContextUtil.getCurUser();
        clientService.updateDeliveryStatusToCompleted(orderId);
        String confirmMessage = "订单已完成";
        modelMap.addAttribute("confirmMessage", confirmMessage);
        modelMap.addAttribute("user",clientUser);
        return "redirect:clientorderdetail?orderId="+orderId;
    }


    @GetMapping("clientpayhistory")
    public String showPayHistory(ModelMap modelMap,
                                 @RequestParam(value = "page", defaultValue = "1") int page,
                                 @RequestParam(value = "size", defaultValue = "8") int size) {
        User clientUser=ServletContextUtil.getCurUser();
        Integer userId=clientUser.getUserId();
        Integer AccountId=clientService.selectAccountById(userId).getAccountId();
        // 获取消费记录列表
        List<Transaction> transactions = clientService.getTransactionsByAccountId(AccountId);
        int totalpages = (int) Math.ceil((double) transactions.size() / size);
        // 获取总消费金额
        BigDecimal totalAmount = clientService.sumExpenseAmountByAccountId(AccountId);
        // 获取总消费次数
        Integer totalCount =clientService.countExpenseRecordsByAccountId(AccountId);
        modelMap.addAttribute("transactions", transactions);
        modelMap.addAttribute("totalAmount", totalAmount);
        modelMap.addAttribute("totalCount", totalCount);
        modelMap.addAttribute("currentPage", page);
        modelMap.addAttribute("totalPages", totalpages);
        modelMap.addAttribute("user",clientUser);
        return "Clients/PayHistory";
    }


    @GetMapping("clientorder")
    public String clientOrder(ModelMap modelMap) {
        User clientUser=ServletContextUtil.getCurUser();
        modelMap.addAttribute("user",clientUser);
        return "Clients/Order";
    }

    //下单
    @PostMapping("clientorder")
    public String clientPostOrder(ModelMap modelMap,@RequestParam("address") String address) {
        User clientUser=ServletContextUtil.getCurUser();
        BigDecimal clientbalance=clientService.selectAccountById(clientUser.getUserId()).getBalance();
        BigDecimal clienttotalexpense=clientService.selectAccountById(clientUser.getUserId()).getTotalExpense();
        Order order=new Order();
        order.setUserId(clientUser.getUserId());
        order.setAddress(address);
        order.setTotalAmount(new BigDecimal("2"));
        Transaction transaction=new Transaction();
        transaction.setAccountId(clientService.selectAccountById(clientUser.getUserId()).getAccountId());
        transaction.setType("expense");
        transaction.setAmount(new BigDecimal("2"));

        if(clientbalance.compareTo(new BigDecimal("2")) < 0) {
            modelMap.addAttribute("Message","余额不足 2 元，请充值");
            return "Clients/Order";
        }
        else {
            clientService.insertOrder(order);
            clientService.updateAccountPay(clientUser.getUserId(),
                    clientbalance.subtract(new BigDecimal("2")),clienttotalexpense.add(new BigDecimal("2")));
            transaction.setOrderId(clientService.selectLatestOrderByUserId(clientUser.getUserId()).getOrderId());
            clientService.insertTransaction(transaction);
        }
        return "redirect:clientmain";
    }

    @GetMapping("clientrecharge")
    public String clientRecharge(ModelMap modelMap) {
        User clientUser=ServletContextUtil.getCurUser();
        modelMap.addAttribute("user",clientUser);
        return "Clients/Recharge";
    }

    //充值
    @PostMapping("clientrecharge")
    public String clientPostRecharge(ModelMap modelMap,@RequestParam("amount") BigDecimal amount) {
        User clientUser=ServletContextUtil.getCurUser();
        Account clientaccount=clientService.selectAccountById(clientUser.getUserId());
        Transaction transaction=new Transaction();
        transaction.setAccountId(clientaccount.getAccountId());
        transaction.setType("recharge");
        transaction.setAmount(amount);
        clientService.updateAccountRecharge(clientUser.getUserId(),
                clientaccount.getTotalRecharge().add(amount),clientaccount.getBalance().add(amount));
        clientService.insertTransactionRecharge(transaction);
        return "redirect:clientuserspace";
    }

    @GetMapping("clientuserinfo")
    public String clientUserinfo(ModelMap modelMap) {
        User clientUser=ServletContextUtil.getCurUser();
        modelMap.addAttribute("user",clientUser);
        return "Clients/UserInfo";
    }
    //改信息
    @PostMapping("clientuserinfo")
    public String clientChangeUserinfo(ModelMap modelMap,User user) {
        User clientUser=ServletContextUtil.getCurUser();
        user.setUserId(clientUser.getUserId());
        clientService.updateUserInfo(user);
        return "redirect:clientuserspace";
    }

    @GetMapping("clientuserpassword")
    public String clientUserPassword(ModelMap modelMap) {
        User clientUser=ServletContextUtil.getCurUser();
        return "Clients/UserPassword";
    }
    //改密码
    @PostMapping("clientuserpassword")
    public String clientChangeUserPassword(ModelMap modelMap,@RequestParam("currentPassword") String oldPassword, @RequestParam("newPassword") String newPassword) {
        User clientUser=ServletContextUtil.getCurUser();
        User user=clientService.selectUserById(clientUser.getUserId());
        Integer id=clientUser.getUserId();
        if(passwordEncoder.matches(oldPassword, user.getPasswordHash())) {
            clientService.updatePassword(passwordEncoder.encode(newPassword),id);
            return "redirect:clientuserspace";
        }else {
            modelMap.addAttribute("errorMessage","原密码错误");
            return "Clients/UserPassword";
        }
    }
    @GetMapping("clientuserspace")
    public String clientUserSpace(ModelMap modelMap) {
        User clientUser = ServletContextUtil.getCurUser();
        User user = clientService.selectUserById(clientUser.getUserId());
        BigDecimal clientUserBalance=clientService.selectAccountById(clientUser.getUserId()).getBalance();
        user.setClientbalance(clientUserBalance);
        modelMap.addAttribute("user",user);
        return "Clients/UserSpace";
    }
}
